package com.hz.filemanager.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.hz.filemanager.R;
import com.hz.filemanager.model.clean.ThridApp;

import java.util.ArrayList;
import java.util.List;

public class ThridAppAdapter extends RecyclerView.Adapter<ThridAppAdapter.ViewHolder>{

    private OnCheckChangedListener listener;
    private List<ThridApp> datas = new ArrayList<>();

    public void setDatas(List<ThridApp> datas){
        this.datas = datas;
    }

    public void setOnCheckChangedListener(OnCheckChangedListener listener){
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.package_item,parent,false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        final ThridApp fixApp = datas.get(position);
        viewHolder.appNameTv.setText(fixApp.getAppName());
        viewHolder.appIconIm.setImageDrawable(fixApp.getAppIcon());
        viewHolder.cb.setChecked(fixApp.isCheck());

        viewHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                fixApp.setCheck(isChecked);

                if (listener != null){
                    listener.onCheckedChanged(isChecked, fixApp.getPackageName());
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{

        private ImageView appIconIm;
        private TextView appNameTv;
        private CheckBox cb;

        public ViewHolder (View view){

            super(view);
            appIconIm = (ImageView) view.findViewById(R.id.app_icon_im);
            appNameTv = (TextView) view.findViewById(R.id.app_name_tv);
            cb = (CheckBox) view.findViewById(R.id.cb);
        }
    }

    /**
     * 获取被选中的app集合
     * @return
     */
    public List<ThridApp> getCheckedDatas(){
        List<ThridApp> checkedApps = new ArrayList<>();
        for(ThridApp app : datas){
            if(app.isCheck()){
                checkedApps.add(app);
            }
        }
        return  checkedApps;
    }

    public interface OnCheckChangedListener{
        /**
         *
         * @param isChecked 被选中的个数
         */
        void onCheckedChanged( boolean isChecked, String packageName);
    }
}
